package org.meichao.config;

import org.meichao.constants.Constants;
import org.meichao.utils.RespInfoUtils;
import org.meichao.utils.vo.RespInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 定义全局异常处理类
 * @ControllerAdvice 捕获所有Controller中抛出的异常
 */

@ControllerAdvice
public class GlobalExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理Exception异常，返回json结果
     * @ExceptionHandler 启动应用后,处理@RequestMapping注解的方法上
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public RespInfo<String> defaultErrorHandler(HttpServletRequest request,Exception e){
        logger.info("================》全局异常：",e);
        return RespInfoUtils.create()
                .respFailure(e instanceof GlobalException ? e.getMessage() : "系统错误,请重试").toRespInfo();
    }

}
